Aliasing `T*` with `char*` is allowed. Is it also allowed the other way around?

Posted by StackedCrooked on Stack Overflow See other posts from Stack Overflow or by StackedCrooked
Published on 2012-09-27T00:45:24Z Indexed on 2012/10/29 23:01 UTC
Read the original article Hit count: 179

Note: This question has been renamed and reduced to make it more focused and readable. Most of the comments refer to the old text.


According to the standard objects of different type may not share the same memory location. So this would not be legal:

int i = 0;
short * s = reinterpret_cast<short*>(&i); // BAD!


The standard however allows an exception to this rule: any object may be accessed through a pointer to char or unsigned char:

int i = 0;
char * c = reinterpret_cast<char*>(&i); // OK

However, it is not clear to me if this is also allowed the other way around. For example:

char * c = read_socket(...);
unsigned * u = reinterpret_cast<unsigned*>(c); // huh?


Summary of the answers

The answer is NO for two reasons:

  1. You an only access an existing object as char*. There is no object in my sample code, only a byte buffer.
  2. The pointer address may not have the right alignment for the target object. In that case dereferencing it would result in undefined behavior. On the Intel and AMD platforms it will result performance overhead. On ARM it will trigger a CPU trap and your program will be terminated!

This is a simplified explanation. For more detailed information see answers by @Luc Danton, @Cheers and hth. - Alf and @David Rodríguez.

© Stack Overflow or respective owner

Related posts about c++

Related posts about c